<?php
namespace app\controller\api;

use app\handler\wechat\ai\ImageMessageHandler;
use app\handler\wechat\ai\SubscribeMessageHandler;
use app\handler\wechat\ai\SupervisorMessageHandler;
use app\handler\wechat\ai\TextMessageHandler;
use app\handler\wechat\ai\VoiceMessageHandler;
use app\services\tools\WechatService;
use EasyWeChat\Kernel\Messages\Message;
use think\Controller;

class Wechat extends Controller
{
    protected $wechat;
    protected $config;

    /**
     * 初始化方法根据参数选择配置的公众号
     */
    public function initialize()
    {
        $account = $this->request->param('account', 'default');
        $this->config = config('wechat.' . $account);
        $wechat = WechatService::getInstance($this->config);
        $this->wechat = $wechat->getWechat();
    }

    /**
     * 响应公众号事件处理
     */
    public function response()
    {
        $this->wechat->server->push(SubscribeMessageHandler::class, Message::EVENT);
        $this->wechat->server->push(new TextMessageHandler($this->config), Message::TEXT);
        $this->wechat->server->push(new ImageMessageHandler($this->config), Message::IMAGE);
        $this->wechat->server->push(new VoiceMessageHandler($this->config), Message::VOICE);
        $this->wechat->server->push(new SupervisorMessageHandler($this->config));
        $response = $this->wechat->server->serve();
        $response->send();
    }
}